package com.example.demo.config;

import com.example.demo.mapper.UserMapper;
import com.example.demo.util.SpringTool;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RolesFilter extends RolesAuthorizationFilter {


    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        UserMapper userMapper = (UserMapper) SpringTool.getBean("userMapper");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        String role = userMapper.getRole(username);
        System.out.println("开始对你的角色进行认定");
        System.out.println(role);
        System.out.println(httpServletRequest.getRequestURI());
        String[] split = httpServletRequest.getRequestURI().split("/");
        if(split.length != 0 && split[0].equalsIgnoreCase(role)){
            return true;
        }else {
            return false;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        System.out.println("你的角色权限不够");
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if(isAjax(request)){
            System.out.println("这是ajax请求");
            httpServletResponse.sendRedirect("/notRole");
        }else {
            System.out.println("这不是ajax请求");
            httpServletResponse.sendRedirect("/page/common/notRole");
        }
        return  false;
    }
    private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
